package cn.xsirl.websocket.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatRoomManager {
    private static Logger log = LoggerFactory.getLogger(ChatRoomManager.class);
    
    public static final ConcurrentHashMap<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>(256);

    /**
     *
     * @param sid
     * @param session
     */
    public static void add(String sid, WebSocketSession session) {
        SESSION_POOL.put(sid, session);
    }

    public static void remove(String sid) {
        SESSION_POOL.remove(sid);
    }

    public static WebSocketSession get(String sid) {
        return SESSION_POOL.get(sid);
    }
    
    /**
     * 广播消息
     * @param message
     */
    public static void broadcast(WebSocketMessage<?> message) {
        log.info("----------- 正在广播消息 ----------");
        ChatRoomManager.SESSION_POOL.forEach((k, v) -> {
            log.info("---------- 用户信息 ----------");
            log.info("用户会话id: {}", k);
            log.info("用户是否在线：{}", v.isOpen());
            if(v.isOpen()) {
                try {
                    v.sendMessage(message);
                } catch(IOException e) {
                    log.error("消息发送失败：{}", e);
                }
            }
        });
    }
}
